import { _decorator, Component, Node } from 'cc'
import { TileMapManager } from '../Tile/TileMapManager'
import { createUINode } from '../Utils'
import levels, { ILevel } from '../Levels'
import DataManager from '../RunTime/DataManager'
import { TILE_HEIGHT, TILE_WIDTH } from '../Tile/TileManager'
import { EventManager } from '../RunTime/EventManager'
import { EVENT_ENUM } from '../Enums'
import { PlayerManager } from '../Player/PlayerManager'
const { ccclass, property } = _decorator

@ccclass('BattleManager')
export class BattleManager extends Component {
  levelProperty: ILevel
  stage: Node

  // 适配屏幕
  adaptPosition() {
    const { mapRowCount, mapColumnCount } = DataManager.getInstance(DataManager)
    const disX = (TILE_WIDTH * mapRowCount) / 2
    const disY = (TILE_HEIGHT * mapColumnCount) / 2 + 220

    this.stage.setPosition(-disX, disY)
  }

  generatePlayer() {
    const playerNode = createUINode('PlayerNode')
    playerNode.setParent(this.stage)

    const playerManager = playerNode.addComponent(PlayerManager)
    playerManager.init()
  }

  generateTileMap() {
    const tileMapNode = createUINode('TileMapManagerNode')
    tileMapNode.setParent(this.stage)

    const tileMapManager = tileMapNode.addComponent(TileMapManager)
    tileMapManager.init()

    this.adaptPosition()
  }

  generateStage() {
    this.stage = createUINode('StageNode')
    this.stage.setParent(this.node)
  }

  initLevel() {
    const instance = DataManager.getInstance(DataManager)
    const order = instance.levelIndex
    const level = levels[`level0${order}`]

    if (level) {
      this.clearLevel()

      this.levelProperty = level
      instance.mapInfo = this.levelProperty.mapInfo
      instance.mapRowCount = this.levelProperty.mapInfo.length || 0
      instance.mapColumnCount = this.levelProperty.mapInfo[0].length || 0

      this.generateTileMap()
      this.generatePlayer()
    }
  }

  nextLevel() {
    DataManager.getInstance(DataManager).levelIndex++
    this.initLevel()
  }

  clearLevel() {
    this.stage.destroyAllChildren()
    DataManager.getInstance(DataManager).reset()
  }

  start() {
    this.generateStage()
    this.initLevel()
  }

  onLoad(): void {
    // 绑定事件
    EventManager.getInstance(EventManager).on(EVENT_ENUM.NEXT_LEVEL, this.nextLevel, this)
  }

  onDestroy(): void {
    // 解绑事件
    EventManager.getInstance(EventManager).off(EVENT_ENUM.NEXT_LEVEL, this.nextLevel)
  }
}
